package com.retailcloud.inventoryservice.service.impl;

import com.retailcloud.commonutils.constant.SyncStatusEnum;
import com.retailcloud.commonutils.constant.UserRedisKeyConstant;
import com.retailcloud.commonutils.dto.ProductSearchVo;
import com.retailcloud.commonutils.dto.ProductionInfoVo;
import com.retailcloud.commonutils.dto.UserDTO;
import com.retailcloud.commonutils.entity.ProductAttributeEntity;
import com.retailcloud.commonutils.exception.RetailCloudException;
import com.retailcloud.commonutils.utils.*;
import com.retailcloud.inventoryservice.feign.ProductElasticSearchFeignService;
import com.retailcloud.inventoryservice.service.ProductAttributeService;
import com.sitech.idworkstarter.IdWorkService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.retailcloud.inventoryservice.dao.ProductInfoDao;
import com.retailcloud.inventoryservice.entity.ProductInfoEntity;
import com.retailcloud.inventoryservice.service.ProductInfoService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;


@Service("productInfoService")
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoDao, ProductInfoEntity> implements ProductInfoService {
    @Resource
    ProductAttributeService productAttributeService;

    @Resource
    IdWorkService idWorkService;

    @Resource
    RedisUtils redisUtils;

    @Resource
    ProductElasticSearchFeignService productElasticSearchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductInfoEntity> page = this.page(
                new Query<ProductInfoEntity>().getPage(params),
                new QueryWrapper<ProductInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Map<String, Object> queryPage(ProductSearchVo productSearchVo) {

        String wechatOpenId = HttpContextUtils.getHttpServletRequest().getHeader("X-User-Name");
        //从缓存中获取用户信息
        UserDTO userDTO = redisUtils.get(UserRedisKeyConstant.USER_TOKEN_USER_KEY + wechatOpenId, UserDTO.class);
        productSearchVo.setTenantId(userDTO.getTenantId());
        Map<String,Object> map= productElasticSearchFeignService.productSearch(productSearchVo);
        if (MapUtils.isNotEmpty(map)) {
            if(!map.containsKey("code")) {
                return map;
            } else{
                throw new RetailCloudException(map.get("message").toString(), Integer.parseInt(map.get("code").toString()));
            }

        } else{
            throw new RetailCloudException("查询失败", 500);
        }

    }

    @Override
    public void saveProductInfo(ProductionInfoVo productionInfoVo) {
        String wechatOpenId = HttpContextUtils.getHttpServletRequest().getHeader("X-User-Name");
        //从缓存中获取用户信息
        UserDTO userDTO = redisUtils.get(UserRedisKeyConstant.USER_TOKEN_USER_KEY + wechatOpenId, UserDTO.class);
        String id = idWorkService.getSEQByKey("id_seq");
        productionInfoVo.setSku(id);
        productionInfoVo.setTenantId(userDTO.getTenantId());
        productionInfoVo.setCreatedBy(userDTO.getWechatOpenid());
        productionInfoVo.setUpdatedBy(userDTO.getWechatOpenid());
        productionInfoVo.setSyncStatus(SyncStatusEnum.PENDING);
        productionInfoVo.setId(id);

        StringBuffer fullAttributeValueStringBuffer = new StringBuffer();

        //批量保存属性信息
        if (!CollectionUtils.isEmpty(productionInfoVo.getProductAttributes())) {
            List<ProductAttributeEntity> productAttributeEntityList = productionInfoVo.getProductAttributes().stream().map(item -> {
                item.setProductId(productionInfoVo.getId());
                item.setCreatedBy(productionInfoVo.getCreatedBy());
                item.setUpdatedBy(productionInfoVo.getUpdatedBy());
                item.setId(idWorkService.getSEQByKey("attr_id_seq"));
                item.setTenantId(userDTO.getTenantId());
                fullAttributeValueStringBuffer.append(item.getAttributeValue());
                fullAttributeValueStringBuffer.append(";");
                return item;
            }).collect(Collectors.toList());
            productAttributeService.saveBatch(productAttributeEntityList);
        }

        productionInfoVo.setFullAttributeValue(fullAttributeValueStringBuffer.toString());
        ProductInfoEntity productionInfo = new ProductInfoEntity();
        BeanUtils.copyProperties(productionInfoVo, productionInfo);

        baseMapper.insert(productionInfo);
        List<ProductionInfoVo> productionInfoVoList = new ArrayList<>();
        productionInfoVoList.add(productionInfoVo);
        //同步索引，异步方法最好
        productElasticSearchFeignService.saveProductElasticSearch(productionInfoVoList);
    }

}
